package com.fast.pay.trade.timerImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;

import com.fast.pay.account.entity.RpSettRecord;
import com.fast.pay.account.enums.SettRecordStatusEnum;
import com.fast.pay.account.service.RpSettHandleService;
import com.fast.pay.account.service.RpSettQueryService;
import com.fast.pay.common.core.enums.TradeStatusEnum;
import com.fast.pay.common.core.page.PageBean;
import com.fast.pay.common.core.page.PageParam;
import com.fast.pay.trade.dao.RpChannelInfoDao;
import com.fast.pay.trade.entity.RpChannelInfo;
import com.fast.pay.trade.entity.RpTradePaymentRecord;
import com.fast.pay.trade.service.RpRemitManagerService;
import com.fast.pay.trade.service.RpTradePaymentManagerService;
import com.fast.pay.trade.service.RpTradePaymentQueryService;
import com.fast.pay.trade.timer.RpTrxSyncManagerService;
import com.fast.pay.trade.vo.PaymentOrderQueryParam;
import com.fast.remote.channel.api.ChannelPayApi;
import com.fast.remote.channel.api.ChannelRemitApi;
import com.fast.remote.channel.vo.PayOrderParam;
import com.fast.remote.channel.vo.RemitOrderParam;
import com.fast.remote.channel.vo.ResultVo;

public class RpTrxSyncManagerServiceImpl implements RpTrxSyncManagerService{
    private static final Logger LOG = LoggerFactory.getLogger(RpTrxSyncManagerServiceImpl.class);

	
	@Autowired
    private RpTradePaymentManagerService rpTradePaymentManagerService;
	
	@Autowired
	private RpSettQueryService rpSettQueryService;
	@Autowired
	private RpSettHandleService rpSettHandleService;
	
	@Autowired
	private RpTradePaymentQueryService rpTradePaymentQueryService;
	
	@Resource(name = "taskExecutor")
    private TaskExecutor taskExecutor;
	
	@Autowired 
	private RpRemitManagerService rpRemitManagerService;
	
	

    @Autowired
    private RpChannelInfoDao rpChannelInfoDao;
    

//	@Override
//	public void createSync(int minute) {
//		
//		Date sdate= new Date();
//		Date edate = new Date();
//		sdate =DateUtils.addMinute(sdate, -2);
//		edate =DateUtils.addMinute(edate, -3);
//		
//	}

	@Override
	public void syncTrxById(String id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void syncTrxByTimes(Date startTime, Date endTime) {
		
		PaymentOrderQueryParam param = new PaymentOrderQueryParam();
		PageParam pageParam = new PageParam();

		String sdateStr = DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss");
		String edateStr = DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss");

		param.setOrderDateBegin(sdateStr);
		param.setOrderDateEnd(edateStr);
		param.setStatus(TradeStatusEnum.WAITING_PAYMENT.name());
		for(;;) {
			PageBean<RpTradePaymentRecord> pRecordPage = rpTradePaymentQueryService.listPaymentRecordPage(pageParam, param);
			LOG.error("补单进行中--"+pRecordPage.getCurrentPage());
			pageParam.setPageNum(pRecordPage.getCurrentPage()+1);
			List<RpTradePaymentRecord> recList = pRecordPage.getRecordList();
			if(recList==null || recList.size()==0)
			for(RpTradePaymentRecord rec : recList) {
				try {
					String channelCode = rec.getPayWayCode();
					if(StringUtils.isEmpty(channelCode)) {
						LOG.error(rec.getMerchantOrderNo()+"订单通道编号不存在----："+channelCode);
						continue;
					}
					RpChannelInfo cinfo = rpChannelInfoDao.selectByMerchantNoAndMerchantOrderNo(channelCode, "PAY");
					if(cinfo==null) {
						LOG.error(rec.getMerchantOrderNo()+"通道信息不存在---："+channelCode);
						continue;
					}
					
					ChannelPayApi api =rpTradePaymentManagerService.getChennelBean(channelCode);
					
					PayOrderParam bankParam = new PayOrderParam();
		            try {
		    			BeanUtils.copyProperties(bankParam, rec);
		    		} catch (Exception e) {
		    			LOG.info("参数组装失败："+rec.getMerchantOrderNo(),e); 
		    			continue;
		    		}
		           Map<String, String> ext = new HashMap<String, String>();
		           ResultVo res = api.query(bankParam, cinfo.getKeyStr(), ext);
		           if(res.getApiFlag() && TradeStatusEnum.SUCCESS.equals( res.getOrderState())) {//支付成功
		        	   LOG.info("订单补单成功："+rec.getMerchantOrderNo());
		        	   rpTradePaymentManagerService.completeScanPayByQuery(rec.getId());
		           }
				} catch (Exception e) {
					LOG.info("订单支付发生异常："+rec.getMerchantOrderNo(),e); 
				}
			}
		}
	}

	@Override
	public void syncRemitById(String id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void syncRemitTimes(Date startTime, Date endTime) {
		
		Map<String, Object> param = new HashMap<>();
		PageParam pageParam = new PageParam();
//		Date sdate= new Date();
//		Date edate = new Date();
//		sdate =DateUtils.addMinute(sdate, -2);
//		edate =DateUtils.addMinute(edate, -3);
		String sdateStr = DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss");
		String edateStr = DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss");

		param.put("status", SettRecordStatusEnum.WAIT_CONFIRM.name());
		param.put("orderDateEnd", sdateStr);
		param.put("orderDateBegin", edateStr);
		for(;;) {
			PageBean<RpSettRecord> pRecordPage = rpSettQueryService.querySettDailyCollectListPage(pageParam, param);
			LOG.error("补单进行中--"+pRecordPage.getCurrentPage());
			pageParam.setPageNum(pRecordPage.getCurrentPage()+1);
			List<RpSettRecord> recList = pRecordPage.getRecordList();
			if(recList==null || recList.size()==0)
			for(RpSettRecord rec : recList) {
				try {
					String channelCode = rec.getPayWayCode();
					if(StringUtils.isEmpty(channelCode)) {
						LOG.error(rec.getTrxNo()+"订单通道编号不存在----："+channelCode);
						continue;
					}
					RpChannelInfo cinfo = rpChannelInfoDao.selectByMerchantNoAndMerchantOrderNo(channelCode, "REMIT");
					if(cinfo==null) {
						LOG.error(rec.getTrxNo()+"通道信息不存在---："+channelCode);
						continue;
					}
					
					ChannelRemitApi api =rpRemitManagerService.getChennelBean(channelCode);
					
					RemitOrderParam bankParam = new RemitOrderParam();
		            try {
		    			BeanUtils.copyProperties(bankParam, rec);
		    		} catch (Exception e) {
		    			LOG.info("参数组装失败："+rec.getTrxNo(),e); 
		    			continue;
		    		}
		           Map<String, String> ext = new HashMap<String, String>();
		           ResultVo res = api.query(bankParam, cinfo.getKeyStr(), ext);
		           if(res.getApiFlag() && TradeStatusEnum.SUCCESS.equals( res.getOrderState())) {//支付成功
		        	   LOG.info("订单补单成功："+rec.getTrxNo());
		        	   rpSettHandleService.remitSucc(rec.getId(),"补单成功");
		           }
				} catch (Exception e) {
					LOG.info("订单支付发生异常："+rec.getTrxNo(),e); 
				}
			}
		}
	}
	
	
	
	

}
